package integration


import nancal.mp.db.mongo.entity.dev.GitData
import nancal.mp.db.mongo.entity.dev.GitFolderData
import nancal.mp.db.mongo.mor
import nancal.mp.service.K8sDeploymentService
import nancal.mp.service.git.impl.GitEaService
import nancal.mp.service.jenkins.JenkinsPublishJob
import nancal.mp.service.jenkins.publish.peek_jar_from_docker
import nbcp.base.annotation.log.MyLogLevel
import nbcp.base.comm.JsonMap
import nbcp.base.comm.const
import nbcp.base.enums.LogLevelScopeEnum
import nbcp.base.extend.*
import nbcp.base.utils.FileUtil
import nbcp.base.utils.ShellUtil
import nbcp.myoql.db.mongo.base.MongoColumnName
import nbcp.myoql.db.mongo.query
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import java.io.File
import java.io.FileWriter


//@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Git17Test : TestBase() {

    @Autowired
    lateinit var gitEaService: GitEaService

    @Autowired
    lateinit var k8sDeploymentService: K8sDeploymentService


    @Test
    @MyLogLevel(LogLevelScopeEnum.WARN)
    fun test_deploy_17() {
        var gitServer = mor.dev.gitServer.query().toEntity();
        var gitDatas = mor.dev.gitData.query().toList();
        var list1 = mutableListOf<String>()

        gitDatas.forEach { gitData ->
            println("# ${gitData.path}")

            gitData.folders.forEach { folder ->
                println("\t ${folder.name}")
                peek_jar2(gitData, folder)
            }
        }
    }


    private fun peek_jar2(
            gitData: GitData,
            folder: GitFolderData
    ) {

        var jobName = (folder.name)
        var basePath = FileUtil.resolvePath("/opt/17", jobName)

        var yamlMap = k8sDeploymentService.getDeploymentYaml("", "default", jobName)
        var container =
                (yamlMap.getValueByWbsPath("spec.template.spec.containers") as List<*>).first() as Map<String, Any?>

        if (container.containsKey("env")) {
            var envs = (container.getValueByWbsPath("env") as List<Map<String, String>>).map {
                it.get("name").AsString() to it.get("value").AsString()
            }.toMap();
        }

        var image = container.getValueByWbsPath("image").AsString()
        var lastIndex = image.lastIndexOf(":")
        var imageName = image.Slice(0, lastIndex)
        var version = image.Slice(lastIndex + 1)

        var log = mor.dev.jenkinsLog.query()
                .where { it.gitData.id mongoEquals gitData.id }
                .where { it.buildInfo.buildFolder mongoEquals folder.path }
                .where { MongoColumnName("buildVersions.dockerImageVersion") mongoEquals version }
                .orderByDesc { it.id }
                .toEntity()!!;

        var task = JenkinsPublishJob(log);

        FileWriter(basePath + "/s.sh").use {
            it.write("docker_image_version=${version}")
            it.write(task.peek_jar_from_docker().toString().replace("＄", "$"))
        }

    }


    private fun peek_jar(
            gitData: GitData,
            folder: GitFolderData
    ) {
        var basePath = "/opt/17"

        var path = FileUtil.resolvePath(basePath,  (folder.name))
        ShellUtil.execRuntimeCommand("mkdir -p " + path)

        var yamlMap = k8sDeploymentService.getDeploymentYaml("", "default", (folder.name))
        var container =
                (yamlMap.getValueByWbsPath("spec.template.spec.containers") as List<*>).first() as Map<String, Any?>
        var envs = (container.getValueByWbsPath("env") as List<Map<String, String>>).map {
            it.get("name").AsString() to it.get("value").AsString()
        }.toMap();

        var image = container.getValueByWbsPath("image").AsString()
        ShellUtil.execRuntimeCommand("docker pull " + image).apply {
            if (this.msg.HasValue) {
                println("拉取镜像失败！")
                return;
            }
        }

        ShellUtil.execRuntimeCommand("docker save -o" + image, path)
        ShellUtil.execRuntimeCommand("tar xvf docker.tar --warning=no-timestamp", path)
        ShellUtil.execRuntimeCommand("rm -rf docker.tar", path)

        var layers = (File(FileUtil.resolvePath(path, "manifest.json")).readText(const.utf8)
                .FromListJson(JsonMap::class.java).first() as Map<String, Any>).get("Layers") as List<String>

        layers.forEach {
            ShellUtil.execRuntimeCommand("tar xvf " + it + " --warning=no-timestamp  -C  docker_tar_dir", path)
        }
    }

}